package org.dromara.school.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.github.yulichang.toolkit.JoinWrappers;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import org.dromara.common.core.domain.model.LoginUser;
import org.dromara.common.core.enums.UserType;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.school.domain.Campus;
import org.dromara.school.domain.Classes;
import org.dromara.school.domain.vo.ClassesVo;
import org.dromara.school.service.IClassesService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.dromara.school.domain.bo.DisciplineBo;
import org.dromara.school.domain.vo.DisciplineVo;
import org.dromara.school.domain.Discipline;
import org.dromara.school.mapper.DisciplineMapper;
import org.dromara.school.service.IDisciplineService;
import com.github.yulichang.base.MPJBaseServiceImpl;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Collection;
import java.util.stream.Collectors;

/**
 * 学科管理Service业务层处理
 *
 * @author Gjb
 * @date 2025-06-05
 */
@RequiredArgsConstructor
@Service
public class DisciplineServiceImpl  extends MPJBaseServiceImpl<DisciplineMapper,Discipline> implements IDisciplineService {

    private final DisciplineMapper baseMapper;

    private final IClassesService classesService;

    /**
     * 查询学科管理
     */
    @Override
    public DisciplineVo queryById(Long disciplineId){

//        return baseMapper.selectVoById(disciplineId);

        Discipline discipline = baseMapper.selectById(disciplineId);

        Map<String, Integer> schoolClassesName = classesService.getSchoolClassesName(discipline.getSchoolCampusId());
        DisciplineVo disciplineVo = new DisciplineVo();
        BeanUtils.copyProperties(discipline, disciplineVo);
        if (StringUtils.isNotNull(discipline.getGrade())) {
            String[] gradeYears = discipline.getGrade().split(",");
            List<String> s = Arrays.stream(gradeYears).map(i -> String.valueOf(schoolClassesName.get(i))).collect(Collectors.toList());
            disciplineVo.setGradesYears(s);
        }

        return disciplineVo;


    }

    /**
     * 查询学科管理列表
     */
    @Override
    public TableDataInfo<DisciplineVo> queryPageList(DisciplineBo bo, PageQuery pageQuery) {
//        LambdaQueryWrapper<Discipline> lqw = buildQueryWrapper(bo);
//        Page<DisciplineVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
//        return TableDataInfo.build(result);
//        MPJLambdaWrapper<Discipline> disciplineMPJLambdaWrapper = new MPJLambdaWrapper<Discipline>()
        MPJLambdaWrapper<Discipline> mpj = JoinWrappers.lambda(Discipline.class)
            .selectAll(Discipline.class)
            .select(Campus::getCampusName)
            .leftJoin(Campus.class, Campus::getCampusId, Discipline::getSchoolCampusId)
            .logicDelToOn();


        if (StringUtils.isNotNull(bo.getSchoolCampusId())) {
            mpj.eq(Discipline::getSchoolCampusId, bo.getSchoolCampusId());
        }
        if (StringUtils.isNotNull(bo.getSubjectName())) {
            mpj.like(Discipline::getSubjectName, bo.getSubjectName());
        }
        if (StringUtils.isNotNull(bo.getClassYear())) {
            Map<Integer, String> schoolGrades = classesService.getSchoolGrades(bo.getSchoolCampusId());
            mpj.like(Discipline::getGrade, schoolGrades.get(Integer.valueOf(bo.getClassYear()[0])));
        }


        LoginUser loginUser = LoginHelper.getLoginUser();
        UserType userType = UserType.getUserType(loginUser.getUserType());
        switch (userType) {
            case SYS_USER:
                break;
            case SCHOOLADMIN:
                //TODO 多校区后续优化
//                List<Integer> campusids = Arrays.asList(loginUser.getSysUser().getSchoolCampusIds().split(",")).stream().map(i -> Integer.valueOf(i)).collect(Collectors.toList());
//                disciplineMPJLambdaWrapper.in(Discipline::getSchoolCampusId, campusids);
                break;
            case TEACHER:
//                List<Integer> campusids = Arrays.asList(loginUser.getSysUser().getSchoolCampusIds().split(",")).stream().map(i -> Integer.valueOf(i)).collect(Collectors.toList());
//                disciplineMPJLambdaWrapper.in(Discipline::getSchoolCampusId,campusids);
                break;
            default:
                return null;
        }

        if(pageQuery.getPageNum()!=null||pageQuery.getPageSize()!=null){
            IPage<DisciplineVo> ipage = baseMapper.selectJoinPage(
                new Page<DisciplineVo>(pageQuery.getPageNum(), pageQuery.getPageSize()),
                DisciplineVo.class, mpj
            );
            TableDataInfo<DisciplineVo> disciplineResult = TableDataInfo.build(ipage);
            return disciplineResult;
        }
        //查询所有学科
        List<DisciplineVo> disciplineVos = baseMapper.selectJoinList(DisciplineVo.class, mpj);
        TableDataInfo<DisciplineVo> disciplineResult = TableDataInfo.build(disciplineVos);
        return disciplineResult;


    }

    /**
     * 查询学科管理列表
     */
    @Override
    public List<DisciplineVo> queryList(DisciplineBo bo) {
        LambdaQueryWrapper<Discipline> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<Discipline> buildQueryWrapper(DisciplineBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<Discipline> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getSubjectName()), Discipline::getSubjectName, bo.getSubjectName());
        lqw.eq(bo.getSchoolCampusId() != null, Discipline::getSchoolCampusId, bo.getSchoolCampusId());
//        lqw.eq(StringUtils.isNotBlank(bo.getGrade()), Discipline::getGrade, bo.getGrade());
        return lqw;
    }

    /**
     * 新增学科管理
     */
    @Override
    public Boolean insertByBo(DisciplineBo bo) {
        Discipline discipline = new Discipline();
        String grades = getGrades(bo);
        discipline.setGrade(grades);
//        discipline.setSubjectName(bo.getSubjectName());
//        discipline.setSchoolCampusId(bo.getSchoolCampusId());
        BeanUtils.copyProperties(bo,discipline);
        boolean flag =  baseMapper.insert(discipline)>0;
        if (flag) {
            bo.setDisciplineId(bo.getDisciplineId());
        }
        return flag;

    }

    private String getGrades(DisciplineBo bo) {
        if (!StringUtils.isEmpty(bo.getClassYear())) {
            Map<Integer, String> schoolGrades = classesService.getSchoolGrades(bo.getSchoolCampusId());
           String grades =  convertYearsToGrades(schoolGrades,bo.getClassYear());
            return grades;
//            List<String> schoolGrades = classesService.getSchoolGrades(bo.getSchoolCampusId());
//            System.out.println(schoolGrades);
//            String grades = CommonUtils.ArrayToString(Arrays.stream(bo.getClassYear()).map(i ->
//                schoolGrades.get(i)
//            ).toArray(String[]::new));
//            return grades;
        }
        return null;
    }


    public static String convertYearsToGrades( Map<Integer, String> schoolGrades,String[] years) {
        return Arrays.stream(years)
            .map(Integer::valueOf)
            .sorted((a, b) -> b.compareTo(a))
            .map(schoolGrades::get)
            .collect(Collectors.joining(","));
    }


    /**
     * 修改学科管理
     */
    @Override
    public Boolean updateByBo(DisciplineBo bo) {
//        Discipline update = MapstructUtils.convert(bo, Discipline.class);
//        validEntityBeforeSave(update);
        Discipline discipline = new Discipline();
        String grades = getGrades(bo);
        discipline.setGrade(grades);
//        discipline.setDisciplineId(bo.getDisciplineId());
//        discipline.setSubjectName(bo.getSubjectName());
//        discipline.setSchoolCampusId(bo.getSchoolCampusId());
        BeanUtils.copyProperties(bo,discipline);
        return baseMapper.updateById(discipline)>0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(Discipline entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除学科管理
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public int insertDisciplineByExcel(Discipline discipline) {
        return baseMapper.insert(discipline);
    }

    @Override
    public List<Discipline> findDisciplineList(Discipline discipline) {
        //拼装查询条件
        LambdaQueryWrapper<Discipline> queryWrapper = new LambdaQueryWrapper<>();
        //根据名称模糊查询
        if (discipline != null) {
            queryWrapper.eq(StringUtils.isNotEmpty(discipline.getSubjectName()), Discipline::getSubjectName, discipline.getSubjectName());
            queryWrapper.eq(StringUtils.isNotEmpty(discipline.getGrade()), Discipline::getGrade, discipline.getGrade());
        }
        return baseMapper.selectList(queryWrapper);
    }

    @Override
    public Discipline findDiscipline(Discipline discipline) {
        LambdaQueryWrapper<Discipline> queryWrapper = new LambdaQueryWrapper<>();
        if (discipline != null) {
            queryWrapper.eq(StringUtils.isNotEmpty(discipline.getSubjectName()), Discipline::getSubjectName, discipline.getSubjectName());
            queryWrapper.eq(StringUtils.isNotNull(discipline.getSchoolCampusId()), Discipline::getSchoolCampusId, discipline.getSchoolCampusId());
        }

        return this.baseMapper.selectOne(queryWrapper);

    }
}
